package com.dzpk.gameserver.module.player;

import com.dzpk.gameserver.action.CommandEnum;
import com.dzpk.gameserver.protocol.MessageStruct;
import com.dzpk.gameserver.util.CommonPackageUtil;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.List;

/**
 * Created by somnus on 16/7/23.
 */
public class Player {

    public int playerId;

    // 客戶端连接
    private volatile IoSession session;

    private String clientIp = "UNKNOW";


    public int getPlayerId() {
        return playerId;
    }

    public void setPlayerId(int playerId) {
        this.playerId = playerId;
    }

    public void sendMessage(CommandEnum msgEnum) {
        sendMessage(msgEnum.getId(), new byte[0]);
    }

    public void sendMessage(CommandEnum msgEnum, com.google.protobuf.GeneratedMessage pbData) {
        sendMessage(msgEnum.getId(), pbData.toByteArray());
    }

    public void sendMessage(CommandEnum msgEnum, byte[] datas) {
        sendMessage(msgEnum.getId(), datas);
    }

    private void sendMessage(int messageId, byte[] data) {
        if (session != null) {
            session.write(CommonPackageUtil.getDataPackage(messageId, data));
        }
    }

    public void sendMessage(IoBuffer data) {
        if (session != null) {
            if ((data instanceof IoBuffer) && ((IoBuffer) data).hasRemaining()) {
                try {
                    session.write(data);
                } catch (IllegalArgumentException e) {
                    System.out.println("empty ....................................sadf");
                }
            }
        }
    }
    public void sendErrorMessage(int code, String... params) {
        MessageStruct.S2CErrorCode.Builder error = MessageStruct.S2CErrorCode.newBuilder();
        error.setErrorCode(code);
        if (params != null && params.length > 0) {
            List<String> args = Arrays.asList(params);
            error.addAllParams(args);
        }
        sendMessage(CommandEnum.S2C_ERR_CODE, error.build());
    }

    public IoSession getSession() {
        return session;
    }

    public void setClientIp(String clientIp) {
        this.clientIp = clientIp;
    }

    public void setSession(IoSession session) {
        if (session != null) {
            this.session = session;
            InetSocketAddress isa = (InetSocketAddress) this.session.getRemoteAddress();
            if(isa != null && isa.getAddress() != null){
                setClientIp(isa.getAddress().getHostAddress());
            }
        }
    }

    public static Player createPlayer(IoSession session){
        Player player = new Player();
        player.setSession(session);
        return player;
    }
}
